<!-- 开支编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="form.id > 0 ? '修改开支' : '新建开支'"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="企业" prop="company">
        <el-input
          clearable
          v-model="form.company"
          placeholder="请选择"
          style="width: 300px"
          readonly
          @click="openCompany"
        />
      </el-form-item>

      <el-form-item label="岗位" prop="position_id">
        <el-select
          v-model="form.position_id"
          class="mr"
          placeholder="请选择"
          style="width: 300px"
        >
          <el-option
            v-for="(item, index) in positionList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            @click="handlePositionChange(index)"
          />
        </el-select>
      </el-form-item>

      <!-- 快捷月份选择 -->
      <el-form-item label="开支所属月份" prop="belongs_date">
        <el-date-picker
          v-model="form.belongs_date"
          type="month"
          placeholder="选择月份"
          style="width: 150px"
          value-format="YYYY-MM"
        />
      </el-form-item>
      <el-form-item label="费用产生日期" prop="cost_date">
        <el-date-picker
          v-model="form.cost_date"
          type="date"
          style="width: 150px"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="分类" prop="cate_id">
        <el-select v-model="form.cate_id" style="width: 200px">
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="金额" prop="amount">
        <el-input v-model="form.amount" style="width: 150px" />
      </el-form-item>

      <el-form-item label="备注">
        <el-input clearable v-model="form.remark" style="width: 400px" />
      </el-form-item>

      <el-form-item label="凭证" prop="images">
        <image-upload :limit="1000" v-model="form.images" />
      </el-form-item>

      <el-form-item label="收款账号" prop="introduction">
        <el-select
          v-model="accounts"
          placeholder="快速选择账号"
          style="width: 250px"
        >
          <el-option
            v-for="(item, index) in accountList"
            :key="index"
            :label="
              item.account_type +
              ' ' +
              item.account_realname +
              ' ' +
              item.account
            "
            :value="item.id"
            @click="accountSelect(index)"
          />
        </el-select>
        <el-button
          type="warning"
          @click="openAccountList"
          style="margin-left: 8px"
        >
          管理账号
        </el-button>
      </el-form-item>
      <el-form-item label="账号类型" prop="pay_account_type">
        <el-select
          clearable
          v-model="form.pay_account_type"
          placeholder="账号类型"
          class="ele-fluid"
          style="width: 150px"
        >
          <el-option label="支付宝" value="支付宝"> 支付宝 </el-option>
          <el-option label="银行卡" value="银行卡"> 银行卡 </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="form.pay_account_type === '银行卡'"
        label="银行名称"
        prop="pay_account_bank"
      >
        <el-input v-model="form.pay_account_bank" style="width: 150px" />
      </el-form-item>

      <el-form-item label="账号姓名" prop="pay_account_realname">
        <el-input v-model="form.pay_account_realname" style="width: 150px" />
      </el-form-item>

      <el-form-item label="收款账号" prop="pay_account">
        <el-input v-model="form.pay_account" style="width: 300px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
    <!-- 选择企业 -->
    <Choose v-model="showCompany" @done="chooseCompanyDone" />

    <account v-model="showAccountList" />
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch, nextTick } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import {
    updateCompanyCost,
    pagePosition,
    pageCompanyCostCate
  } from '@/api/company';
  import { pageAdminAccount } from '@/api/oa';
  import Choose from './chooseCompany.vue';
  import Account from '@/views/oa/cost/components/account.vue';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields, assignFields] = useFormData({
    id: 0,
    cate_id: '',
    site_id: '',
    tenant_id: '',
    company_id: '',
    company: '',
    position: '',
    position_id: '',
    amount: '',
    images: '',
    pay_account: '',
    pay_account_bank: '',
    pay_account_realname: '',
    pay_account_type: '',
    cost_date: '',
    belongs_date: ''
  });

  const accountList = ref([]);
  const accounts = ref([]);

  /** 当前所选岗位信息 */
  const currentPosition = ref([]);
  const company = ref([]);
  /** 选择企业 */
  const showCompany = ref(false);
  const openCompany = () => {
    showCompany.value = true;
  };
  const chooseCompanyDone = (e) => {
    form.company = e.company_name;
    form.company_id = e.id;
    form.tenant_id = e.tenant_id;
    form.site_id = e.site_id;
    company.value = e;
    // form.position = '';
    form.position_id = '';
    showCompany.value = false;
    getCompanyPosition();
  };

  /** 职位 */
  const positionList = ref([]);
  const getCompanyPosition = () => {
    pagePosition({
      status: 1,
      company_id: form.company_id,
      page: 1,
      limit: 99999999
    })
      .then((res) => {
        positionList.value = res.list;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  const cateList = ref([]);
  const getCateList = () => {
    pageCompanyCostCate({})
      .then((res) => {
        cateList.value = res.list;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  const showAccountList = ref(false);
  const openAccountList = () => {
    showAccountList.value = true;
  };

  /** 选择职位后 **/
  const handlePositionChange = (i) => {
    form.position = positionList.value[i].title;
    currentPosition.value = positionList.value[i];
  };

  /** 获取角色数据 */
  const getAccount = () => {
    pageAdminAccount({})
      .then((res) => {
        accountList.value = res.list;
      })
      .catch((e) => {
        EleMessage.error(e.message);
      });
  };

  const accountSelect = (index) => {
    var row = accountList.value[index];
    form.pay_account = row.account;
    form.pay_account_bank = row.bank;
    form.pay_account_type = row.account_type;
    form.pay_account_realname = row.account_realname;
  };

  /** 表单验证规则 */
  const rules = reactive({
    company: [
      {
        required: true,
        message: '请选择1个项目',
        type: 'string',
        trigger: 'blur'
      }
    ],

    cost_date: [
      {
        required: true,
        message: '请选择费用产生日期',
        type: 'string',
        trigger: 'blur'
      }
    ],

    amount: [
      {
        required: true,
        message: '请填写金额',
        type: 'string',
        trigger: 'blur'
      }
    ],
    cate_id: [
      {
        required: true,
        message: '请选择分类',
        type: 'int',
        trigger: 'blur'
      }
    ],
    images: [
      {
        required: true,
        message: '请上传凭证',
        type: 'string',
        trigger: 'blur'
      }
    ],

    belongs_date: [
      {
        required: true,
        message: '请选择所属月份',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;

      updateCompanyCost(form)
        .then((msg) => {
          loading.value = false;
          EleMessage.success(msg);
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        getAccount();
        getCateList();
        if (props.data) {
          assignFields({
            ...props.data
          });
          nextTick(() => {
            getCompanyPosition();
          });
        }
      } else {
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
